package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.SystemMenuDao;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SystemMenuServiceImpl implements SystemMenuService {

	@Autowired
	SystemMenuDao systemMenuDao;

	@Override
	public List<Map<String, Object>> getMenuList(String username) {

		List<Map<String, Object>> mapList = new ArrayList<>();
		//1.根据用户名查询对应的角色
		SysUser sysUser = systemMenuDao.findByUsername(username);

		System.out.println("sysUser===========" + sysUser.toString());

		/*"path": "2",
		"title": "会员管理",
		"icon":"fa-user-md",
		"children": [
			{
				"path": "/2-1",
				"title": "会员档案",
				"linkUrl":"member.html",
				"children":[]
			}*/

		List<Menu> menuParentList = new ArrayList<>();
		List<Menu> menuChildrenList = new ArrayList<>();

		for (Role role : sysUser.getRoles()) {
			for (Menu menu : role.getMenus()
					) {
				//将子菜单和父菜单区分
				if (menu.getParentMenuId() == null) {//父级菜单
					menuParentList.add(menu);
				} else {//子菜单
					menuChildrenList.add(menu);
				}
			}
		}

		//将父菜单中对应的子菜单放入其中
		for (Menu menuParent:menuParentList
			 ) {
			for (Menu menuChildren:menuChildrenList
				 ) {
				if(menuChildren.getParentMenuId() == menuParent.getId()){
					menuParent.getChildren().add(menuChildren);
				}
			}

		}

		//拼写mapList信息
		for (Menu menuParent:menuParentList
				) {

			Map<String, Object> map = new HashMap<>();


			map.put("path", menuParent.getPath());
			map.put("title", menuParent.getName());
			map.put("icon", menuParent.getIcon());




			List<Map<String, Object>> mapListChildren = new ArrayList<>();
			for (Menu menuChildren : menuParent.getChildren()
					) {
				Map<String, Object> mapChildren = new HashMap<>();
				mapChildren.put("path", menuChildren.getPath());
				mapChildren.put("title", menuChildren.getName());
				mapChildren.put("linkUrl", menuChildren.getLinkUrl());
				mapChildren.put("children", "1");
				mapListChildren.add(mapChildren);
			}

			map.put("children", mapListChildren);

			mapList.add(map);
		}
		System.out.println("mapList======="+mapList.toString());
		return mapList;
	}

}
